package com.myzj.sportplay.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

/**
 * 邮件类
 */

@Service
public class SendMail {

    @Autowired
    JavaMailSender javaMailSender; // 引入配置文件属性

    @Resource //同上
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String sendUsername;



    /**
     * 以html模板形式,发送自定义格式给收件人
     * @param to 收件人
     * @param subject 主题
     * @param textHtml 模板html
     * @param activationUrl 模板html所需链接
     * @return
     */
    public String sendMsg(String to,String subject,String textHtml,String activationUrl){
        try{
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            //邮件发送人
            helper.setFrom(sendUsername);
            //邮件接收人
            helper.setTo(to);
            //邮件接主题
            helper.setSubject(subject);
            Context context = new Context();
            // 邮件中传递的链接
            context.setVariable("activationUrl",activationUrl);
            // 映射html文件
            String text = templateEngine.process(textHtml,context);
            //邮件接内容
            helper.setText(text,true);
            javaMailSender.send(mimeMessage);
            return "1";
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送邮件失败");
            return "0";
        }
    }



    /**
     * 简单发送邮件
     * @param to 收件人
     * @param subject 主题
     * @param text 内容
     * @return
     */
    public String sendMsg(String to,String subject,String text){
        try{
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            //邮件发送人
            simpleMailMessage.setFrom(sendUsername);
            //邮件接收人
            simpleMailMessage.setTo(to);
            //邮件接主题
            simpleMailMessage.setSubject(subject);
            //邮件接内容
            simpleMailMessage.setText(text);
            javaMailSender.send(simpleMailMessage);
            return "1";
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送邮件失败");
            return "0";
        }
    }

}
